<template>
    <div>
        <div class="help-head">
            <div>
                <span>帮助中心FAQ</span>
                <span>APP常见问题的疑问解答</span>
            </div>
            <div>最近发布</div>
        </div>
        <div class="help-main">
            <div class="help-left">
                <el-card class="operate-container" shadow="never">
                    <span class="btn-list">类别</span>
                    <div>
                        <el-button v-if="!isOneS" size="mini" class="btn-add" @click="handleSort()" >排序</el-button>
                        <el-button v-if="isOneS" size="mini" class="btn-add" @click="handleSortC()" >取消</el-button>
                        <el-button style="background-color: #4099ef;color: #fff;" v-if="isOneS" size="mini" class="btn-add" @click="handleSortS()" >提交</el-button>
                        <el-button size="mini" class="btn-add" @click="handleAdd()" >新增</el-button>
                    </div>
                </el-card>
                <div class="table-container">
                    <el-table ref="firstTable"
                                class="lTable"
                                :data="listLei"
                                @row-click="handleRowClick"
                                :row-class-name="tableRowClassName"
                                style="width: 100%;"
                                v-loading="listLoading" border>
                        <el-table-column label="拖拽排序" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-s-operation"></i>
                            </template>
                        </el-table-column>
                        <el-table-column label="类别名称（繁体中文）" align="center">
                            <template slot-scope="scope">{{scope.row.nameZhHk}}</template>
                        </el-table-column>
                        <el-table-column label="操作" width="180" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini"
                                        type="text"
                                        @click="handleEdite(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        @click="handleDelete(scope.$index, scope.row, 1)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="help-right">
                <el-card class="operate-container" shadow="never">
                    <span class="btn-list">对应问题</span>
                    <div>
                        <el-button v-if="!isTwoS" size="mini" class="btn-add" @click="handleSortTwo()" >排序</el-button>
                        <el-button v-if="isTwoS" size="mini" class="btn-add" @click="handleSortTwoC()" >取消</el-button>
                        <el-button style="background-color: #4099ef;color: #fff;" v-if="isTwoS" size="mini" class="btn-add" @click="handleSortTwoS()" >提交</el-button>
                        <el-button size="mini" class="btn-add" @click="handleAddTwo()" >新增</el-button>
                    </div>
                </el-card>
                <div class="table-container">
                    <el-table ref="firstTable"
                                class="qTable"
                                :data="listQ"
                                v-loading="listLoading" border>
                        <el-table-column label="拖拽排序" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-s-operation"></i>
                            </template>
                        </el-table-column>
                        <el-table-column label="问题描述（繁体中文）" align="center">
                            <template slot-scope="scope">{{scope.row.titleZhHk}}</template>
                        </el-table-column>
                        <el-table-column label="问题描述（简体中文）" align="center">
                            <template slot-scope="scope">{{scope.row.titleZhCn}}</template>
                        </el-table-column>
                        <el-table-column label="复制链接" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-paperclip" style="color: #409EFF;cursor: pointer;" @click="handleApk(scope.$index, scope.row)"></i>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini"
                                        type="text"
                                        @click="handleEditeQ(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        @click="handleDelete(scope.$index, scope.row, 2)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <el-dialog
            title="添加类别/编辑类别"
            :visible.sync="cagVisible"
            width="40%">
            <el-form :model="addCag"
                    :rules="rules"
                    ref="cagForm"
                    label-width="180px" size="small"  class="demo-ruleForm">
                <el-form-item label="类别名称（繁体中文）：" prop="nameZhHk">
                    <el-input v-model="addCag.nameZhHk" style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="类别名称（简体中文）：" prop="nameZhCn">
                    <el-input v-model="addCag.nameZhCn" style="width: 250px"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cagVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handlePublishConfirm('cagForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="添加/编辑FAQ"
            :visible.sync="publishVisible"
            width="75%">
            <el-form :model="publishList"
                    ref="publishForm"
                    label-width="180px" size="small">
                <el-form-item label="所属类别：">
                    <el-select v-model="publishList.categoryId" placeholder="请选择所属类别">
                        <el-option
                            v-for="item in listLei"
                            :key="item.id"
                            :label="item.nameZhHk"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="问题（繁体中文）：" prop="titleZhHk">
                    <el-input v-model="publishList.titleZhHk" style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="弹窗介绍内容（繁体中文）: " prop="contentZhHk" label-width="105px">
                    <EditorHK :height="300" v-model="publishList.contentZhHk"></EditorHK>
                </el-form-item>
                <el-form-item label="问题（简体中文）：" prop="titleZhCn">
                    <el-input v-model="publishList.titleZhCn" style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="弹窗介绍内容（简体中文）: " prop="contentZhCn" label-width="105px">
                    <Editor :height="300" v-model="publishList.contentZhCn"></Editor>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="publishVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handlePublishDoc('publishForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { docList, categoriesList, categoriesAdd, categoriesDelete, docAdd, docUpdate, categoriesUpdate, docSort, categoriesSort, fetchAllResourceList } from '@/api/app';
import Editor from '@/components/Editor';
import EditorHK from '@/components/EditorHK';
import {formatDate} from '@/utils/date';
import Sortable from 'sortablejs';
export default {
    name: 'help',
    components: {
        Editor,
        EditorHK
    },
    data() {
        return {
            listQuery: {
                pageNum	: 1,
                pageSize: -1
            },
            docQuery: {
                pageNum	: 1,
                pageSize: -1,
                categoryId: null
            },
            listLei: [],
            listLoading: false,
            activeIndex: 0,
            listQ: [],
            cagVisible: false,
            addCag: {
                nameZhHk: null,
                nameZhCn: null
            },
            rules: {
                nameZhHk: [
                    { required: true, message: '请填写类别名称（繁体中文）' }
                ],
                nameZhCn: [
                    { required: true, message: '请填写类别名称（简体中文）' }
                ],
            },
            publishVisible: false,
            publishList: {
                titleZhHk: null,
                titleZhCn: null,
                contentZhHk: null,
                contentZhCn: null,
                categoryId: null,
            },
            moduleId: null,
            isAdd: true,
            isTwoS: false,
            isOneS: false,
            currentRow: {id: null},
            leiSort: [],
            qSort: [],
            sortShowOne: null,
            sortShowTwo: null,
            btnMenu: {
                edit: true,
                delete: true,
            },
        }
    },
    created() {
        const menu = JSON.parse(localStorage.getItem('listMenu'));
        const item = menu.filter(item => item.title === '帮助中心FAQ')[0];
        fetchAllResourceList({menuId: item.id }).then(res => {
            res.data.forEach(dom => {
            if (dom.component === '' && dom.name === '后台角色管理') {
                this.btnMenu.edit = false;
            }
            if (dom.component === '' && dom.name === '后台角色删除') {
                this.btnMenu.delete = false;
            }
            });
        });
        this.categoriesInfo();
    },
    mounted() {
        // this.$nextTick(() => {
        //     const el = this.$el.querySelector('.lTable .el-table__body-wrapper tbody');
        //     Sortable.create(el, {
        //         onEnd: (event) => {
        //             const { oldIndex, newIndex } = event;
        //             this.rowDrop(oldIndex, newIndex);
        //         }
        //     })
        // });
        // this.$nextTick(() => {
        //     const el = this.$el.querySelector('.qTable .el-table__body-wrapper tbody');
        //     Sortable.create(el, {
        //         onEnd: (event) => {
        //             const { oldIndex, newIndex } = event;
        //             this.rowDropTwo(oldIndex, newIndex);
        //         }
        //     })
        // });
    },
    filters: {
        formatDateTime(time) {
          if (time == null || time === '') {
            return '-';
          }
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }
    },
    methods: {
        handleRowClick(row, column, event) {
            this.docQuery.categoryId = row['id'];
            this.docInfo();
            this.currentRow = row;
        },
        tableRowClassName({row, rowIndex}) {
            if (row.id === this.currentRow['id']) {
                return 'current-row';
            }
            return '';
        },
        rowDrop(oldIndex, newIndex) {
            this.isOneS = true;
            if (this.leiSort.length === 0) {
                this.leiSort = JSON.parse(JSON.stringify(this.listLei));
            } else {
                this.leiSort = JSON.parse(JSON.stringify(this.leiSort));
            }
            const movedItem = this.leiSort.splice(oldIndex, 1)[0];
            this.leiSort.splice(newIndex, 0, {id: movedItem.id, nameZhCn: movedItem.nameZhCn, nameZhHk: movedItem.nameZhHk});
            // console.log(this.listLei, this.leiSort, movedItem, oldIndex, newIndex);
            // this.listLei = arr;
        },
        rowDropTwo(oldIndex, newIndex) {
            this.isTwoS = true;
            if (this.qSort.length === 0) {
                this.qSort = JSON.parse(JSON.stringify(this.listQ));
            } else {
                this.qSort = JSON.parse(JSON.stringify(this.qSort));
            }
            const movedItem = this.qSort.splice(oldIndex, 1)[0];
            this.qSort.splice(newIndex, 0, movedItem);
            // console.log(this.listQ, oldIndex, newIndex);
        },
        handlePublishConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAdd) {
                        categoriesAdd(this.addCag).then(res => {
                            this.cagVisible = false;
                            this.categoriesInfo();
                        })
                    } else {
                        categoriesUpdate(this.addCag).then(res => {
                            this.cagVisible = false;
                            this.categoriesInfo();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        handlePublishDoc(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAdd) {
                        docAdd(this.publishList).then(res => {
                            this.publishVisible = false;
                            this.docInfo();
                        })
                    } else {
                        docUpdate(this.publishList).then(res => {
                            this.publishVisible = false;
                            this.docInfo();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        docInfo() {
            docList(this.docQuery).then(res => {
                this.listQ = res.data.records;
                this.qSort = this.listQ;
            });
        },
        categoriesInfo() {
            categoriesList(this.listQuery).then(res => {
                this.listLei = res.data.records;
                this.leiSort = this.listLei;
                if (this.listLei.length > 0) {
                    this.docQuery.categoryId = this.listLei[0]['id'];
                    this.currentRow.id = this.listLei[0]['id'];
                    this.docInfo();
                }
            })
        },
        handleSort() {
            const el = this.$el.querySelector('.lTable .el-table__body-wrapper tbody');
            this.sortShowOne = Sortable.create(el, {
                onEnd: (event) => {
                    const { oldIndex, newIndex } = event;
                    this.rowDrop(oldIndex, newIndex);
                }
            })
            this.isOneS = true;
        },
        handleSortC() {
            this.sortShowOne.destroy();
            this.isOneS = false;
            this.categoriesInfo();
        },
        handleSortS() {
            categoriesSort(this.leiSort).then(res => {
                this.isOneS = false;
                this.sortShowOne.destroy();
                // this.categoriesInfo();
                this.$message({
                    type: 'success',
                    message: '排序成功!'
                });
            });
        },
        handleSortTwo() {
            const el = this.$el.querySelector('.qTable .el-table__body-wrapper tbody');
            this.sortShowTwo = Sortable.create(el, {
                onEnd: (event) => {
                    const { oldIndex, newIndex } = event;
                    this.rowDropTwo(oldIndex, newIndex);
                }
            })
            this.isTwoS = true;
        },
        handleSortTwoC() {
            this.sortShowTwo.destroy();
            this.isTwoS = false;
            this.docInfo();
        },
        handleSortTwoS() {
            docSort(this.qSort).then(res => {
                this.isTwoS = false;
                this.sortShowTwo.destroy();
                // this.docInfo();
                this.$message({
                    type: 'success',
                    message: '排序成功!'
                });
            });
        },
        handleAdd() {
            this.cagVisible = true;
            this.isAdd = true;
            this.addCag = {
                nameZhHk: null,
                nameZhCn: null
            };
        },
        handleAddTwo() {
            this.publishVisible = true;
            this.isAdd = true;
            this.publishList = {
                titleZhHk: null,
                titleZhCn: null,
                contentZhHk: null,
                contentZhCn: null,
                categoryId: null,
            };
        },
        async handleApk(index, row) {
            try {
                await navigator.clipboard.writeText(row.urlZhHk);
                this.$message({
                    type: 'success',
                    message: '链接已复制！'
                });
            } catch (error) {
                console.log('复制失败');
            }
        },
        handleEdite(index, row) {
            this.cagVisible = true;
            this.addCag = JSON.parse(JSON.stringify(row));
            this.isAdd = false;
        },
        handleEditeQ(index, row) {
            this.publishVisible = true;
            this.publishList = JSON.parse(JSON.stringify(row));
            this.isAdd = false;
        },
        handleDelete(index, row, type) {
            this.$confirm('是否要删除该数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                categoriesDelete({id: row.id, type: type}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.categoriesInfo();
                });
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.current-row {
  background-color: #f0f9eb;
}
.help-head {
    padding: 40px;
    display: flex;
    justify-content: space-between;
}
.help-main {
    display: flex;
    padding: 0 20px;
    .help-left {
        width: 550px;
        margin-right: 20px;
    }
    .help-right {
        flex: 1;
    }
}
</style>
